"use server";

import { eq } from "drizzle-orm";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";

import { createClient } from "@/lib/supabase/server";
import {
  roles,
  userProfiles,
  UserProfileSchema,
  userRoles,
  UserRoleSchema,
  users,
  userSchema,
} from "@supersavely/db/schema";
import { db } from "@/lib/db";
import { hash } from "bcrypt";

export async function signup(formData: FormData) {
  const supabase = createClient();

  // type-casting here for convenience
  // in practice, you should validate your inputs
  const data = {
    email: formData.get("email") as string,
    password: formData.get("password") as string,
  };

  console.log(data);

  if (!process.env.LOCAL_AUTH) {
    const { error } = await supabase.auth.signUp(data);
    console.error(error);
    if (error) {
      redirect("/error");
    }
  } else {
    data.passwordHash = await hash(data.password, 10);
    data.mode = "signUp";
    data.name = data.email;
    console.log(data);

    const validateData = userSchema.parse(data);
    console.log(validateData);
    if (validateData.mode === "signUp") {
      await db
        .insert(users)
        .values(validateData)
        .catch((e) => {
          console.error(e);
          redirect("/error");
        });
      const userId = (
        await db.select().from(users).where(eq(users.email, validateData.email))
      )[0].id;
      const defaultRoleId = (
        await db.select().from(roles).where(eq(roles.name, "User"))
      )[0].id;
      const dataRole: Omit<
        Extract<UserRoleSchema, { mode: "addUserRole" }>,
        "mode"
      > = {
        userId: userId,
        roleId: defaultRoleId,
      };
      await db
        .insert(userRoles)
        .values(dataRole)
        .catch((e) => {
          console.error(e);
          redirect("/error");
        });
      const dataProfile: Omit<
        Extract<UserProfileSchema, { mode: "addUserProfile" }>,
        "mode"
      > = {
        userId: userId,
      };
      await db
        .insert(userProfiles)
        .values(dataProfile)
        .catch((e) => {
          console.error(e);
          redirect("/error");
        });
    }
  }

  revalidatePath("/", "layout");
  redirect("/auth/login");
}
